package com.aek.aekdroid;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.aek.aekdroid.data.Match;

public class MatchReader {
	public static final String TAG = "MatchReader";
	public ArrayList<Match> matches = new ArrayList<Match>();
	private String url;

	public MatchReader(String url) {
		this.url = url;

	}

	public void read() {
		MyLog.d(TAG, "Reading url : " + url);
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		InputStream in = null;
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			URL u = new URL(url);
			URLConnection urlConnection = u.openConnection();
			in = new BufferedInputStream(urlConnection.getInputStream());
			Document doc = db.parse(in);
			NodeList nodelist = doc.getElementsByTagName("matches");
			Element root = (Element) nodelist.item(0);
			String nv = root.getAttribute("version");
			AekDroidApplication.newVersion = nv != null ? nv : "0";
			MyLog.d(TAG, "Current available version: " + AekDroidApplication.newVersion);
			int matchesNum = doc.getElementsByTagName("match").getLength();
			NodeList matchesEl = doc.getElementsByTagName("match");
			MyLog.d(TAG, "matches:" + matchesNum);
			for (int i = 0; i < matchesNum; i++) {
				Match match = new Match((Element) matchesEl.item(i));
				matches.add(match);
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}
